package beer.coder.walawala.persist;

import beer.coder.walawala.common.config.ApplicationConfigure;
import beer.coder.walawala.common.constant.Constant;
import com.alibaba.fastjson.JSONReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 读取应用配置信息.
 *
 * @author amath0312
 * @version 1.0
 * @date 2019-10-24 22:21
 */
public class ConfigureReader {

  protected File file;

  public ConfigureReader(String file) {
    this.file = new File(file);
  }

  public ConfigureReader(File file) {
    this.file = file;
  }

  public ConfigureReader() {

  }

  /**
   * 从指定配置文件中读取配置信息（JSON反序列化）.
   *
   * @return 配置信息
   */
  public ApplicationConfigure read() throws IOException {
    if (this.file == null) {
      throw new NullPointerException("配置文件不能为空");
    }

    if (!this.file.exists()) {
      if (this.file.getParentFile() != null && !this.file.getParentFile().exists()) {
        this.file.getParentFile().mkdirs();
      }
      try (FileOutputStream fos = new FileOutputStream(file)) {
        fos.write("{}".getBytes(Constant.ENCODING));
        fos.flush();
      }
    }

    if (!this.file.isFile()) {
      throw new IllegalArgumentException("配置文件不存在或文件类型不正确: " + this.file.getAbsolutePath());
    }

    ApplicationConfigure configure = null;
    try (JSONReader reader = new JSONReader(new InputStreamReader(new FileInputStream(file), Constant.ENCODING))) {
      configure = reader.readObject(ApplicationConfigure.class);
      ConfigureUtil.fillDefaultValues(configure);
    }

    return configure;
  }

  public File getFile() {
    return file;
  }

  public void setFile(File file) {
    this.file = file;
  }
}
